#include "OneDimPlot.h"

#include "TH1F.h"
#include "TCanvas.h"

void DrawOneDimPlot(std::string name, YAML::Node config, TChain* chain)
{
    //Histogram
    int bins = config["Bins"].as<int>(100);
    std::pair<double, double> range = std::pair<double, double>(config["Range"][0].as<double>(0), config["Range"][1].as<double>(5));
    TH1F* thOneDim = new TH1F(name.c_str(), "", bins, range.first, range.second);
    std::string branchName = config["BranchName"].as<std::string>(name);
    std::string cut = config["Cut"].as<std::string>("1");
    chain->Project(name.c_str(), branchName.c_str(), cut.c_str());

    //Title
    std::stringstream xTitleStream, yTitleStream;
    xTitleStream << config["XTitle"].as<std::string>(name);
    yTitleStream << config["YTitle"].as<std::string>("Candidates");
    yTitleStream.precision(2);
    yTitleStream.setf(std::ios::fixed);
    if (config["Unit"].IsScalar())
    {
        xTitleStream << " / (" << config["Unit"].as<std::string>() << ")";
        yTitleStream << " / (" << (range.second - range.first) / double(bins) << " " << config["Unit"].as<std::string>() << ")";
    }
    thOneDim->GetXaxis()->SetTitle(xTitleStream.str().c_str());
    thOneDim->GetYaxis()->SetTitle(yTitleStream.str().c_str());

    //Draw
    TCanvas* can = new TCanvas("can", "", 800, 600);
    can->cd();
    thOneDim->Draw(config["DrawOption"].as<std::string>("HIST").c_str());

    //Save
    std::stringstream plotStream;
    std::string plotType = config["PlotType"].as<std::string>("eps");
    plotStream << "ezDraw_OneDim_" << name << "." << plotType;
    std::string plotName = config["PlotName"].as<std::string>(plotStream.str());
    can->SaveAs(plotName.c_str());

    delete thOneDim;
    delete can;
}
